<template>
  <div class="container">
    <div class="left_container">
      <div class="add">
        <i class="el-icon-plus" @click="addFirst"></i>
      </div>
      <div class="label">
        <span>分销名称</span>
        <span>操作</span>
      </div>
      <div class="menu">
        <el-tree
          :data="menuList"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <div
            class="custom-tree-node"
            slot-scope="{ node, data }"
            @click="customHandle(data)"
            style="width: 100%;display: flex;align-items: center;"
            :style="{
              backgroundColor: currentCompanyId == data.id ? '#f3f6fa' : ''
            }"
          >
            <el-tooltip
              class="item"
              effect="dark"
              :content="data.label"
              placement="left"
            >
              <div class="label_item">
                {{ data.label }}
              </div>
            </el-tooltip>
            <span style="position: absolute;right: 0;">
              <!-- <el-button
                type="text"
                size="mini"
                @click.stop="append(data)"
                v-if="data.parentID == 0"
              >
                <i class="el-icon-plus"></i>
              </el-button> -->
              <el-button type="text" size="mini" @click.stop="editHandle(data)">
                <i class="el-icon-edit"></i>
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click.stop="detailHandle(data)"
              >
                <i class="el-icon-document"></i>
              </el-button>
              <!-- <el-button
                type="text"
                size="mini"
                @click.stop="shareHandle(data)"
              >
                <i class="el-icon-share"></i>
              </el-button> -->
              <el-button type="text" size="mini" @click.stop="remove(data)">
                <i class="el-icon-delete" style="color: red;"></i>
              </el-button>
            </span>
          </div>
        </el-tree>
      </div>
    </div>

    <!-- 分销列表 -->
    <div class="right_container">
      <div class="nav" v-if="currentCompanyId">
        <div class="company">
          <span>当前分销：</span>
          <el-tag>{{ currentCompanyName }}</el-tag>
        </div>
      </div>
      <div style="margin-top: 10px;">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#F3F6FA' }"
          max-height="600"
        >
          <el-table-column prop="name" label="客户名" align="center">
          </el-table-column>
          <el-table-column prop="phone" label="客户手机号" align="center">
          </el-table-column>
          <el-table-column prop="createTime" label="加入时间" align="center">
          </el-table-column>
          <el-table-column prop="shareName" label="分享人" align="center">
          </el-table-column>
          <!-- <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="viewDetail(scope.row.id)"
                style="color: #409eff;"
                >查看</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div style="position: absolute;bottom: 20px;left: 30%;">
        <!-- 分页组件 -->
        <Pagination
          v-bind:child-msg="pageparmA"
          @callFather="callFatherA"
        ></Pagination>
      </div>
    </div>

    <!-- 新增一级/二级分销 -->
    <el-dialog
      :title="distributionTitle"
      :visible.sync="distributionVisible"
      width="60%"
      :before-close="closeForm"
    >
      <el-form
        :model="distributionForm"
        status-icon
        :rules="agentRules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <div class="distribution_container">
          <div class="collection">
            <div class="company_item">
              <div class="item_left">
                <div class="label">
                  <div>
                    <i class="el-icon-connection"></i>
                  </div>
                  <div style="margin-left: 10px;">分销名称</div>
                </div>
              </div>
              <div class="item_right">
                <el-form-item
                  label-width="0"
                  style="width: 100%;margin: 0 auto;"
                  prop="name"
                >
                  <el-input
                    v-model="distributionForm.name"
                    style="width: 100%;"
                    placeholder="请输入分销名"
                  ></el-input>
                </el-form-item>
              </div>
            </div>
            <div class="company_item">
              <div class="item_left">
                <div class="label">
                  <div>
                    <i class="el-icon-office-building"></i>
                  </div>
                  <div style="margin-left: 10px;">主体公司</div>
                </div>
              </div>
              <div class="item_right">
                <el-form-item
                  label-width="0"
                  style="width: 100%;margin: 0 auto;"
                  prop="companyID"
                >
                  <el-select
                    style="width: 100%;"
                    v-model="distributionForm.companyID"
                    filterable
                    remote
                    placeholder="请选择"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    @change="getCompanyList()"
                    :disabled="distributionForm.id"
                  >
                    <el-option
                      v-for="item in companyList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <div style="display:flex;justify-content:space-between">
                        <span>{{ item.name }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="collection" v-if="editFlag">
            <div class="company_item">
              <div class="item_left">
                <div class="label">
                  <div>
                    <i class="el-icon-connection"></i>
                  </div>
                  <div style="margin-left: 10px;">负责人</div>
                </div>
              </div>
              <div class="item_right">
                <el-form-item
                  label-width="0"
                  style="width: 100%;margin: 0 auto;"
                  prop="name"
                >
                  <div style="margin-left: 5px;">
                    {{ principalPerson.userName }}
                  </div>
                </el-form-item>
              </div>
            </div>
            <div class="company_item">
              <div class="item_left">
                <div class="label">
                  <div>
                    <i class="el-icon-connection"></i>
                  </div>
                  <div style="margin-left: 10px;">负责人手机号</div>
                </div>
              </div>
              <div class="item_right">
                <el-form-item
                  label-width="0"
                  style="width: 100%;margin: 0 auto;"
                  prop="name"
                >
                  <div style="margin-left: 5px;">
                    {{ principalPerson.phone }}
                  </div>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex;justify-content: flex-end;"
      >
        <el-button @click="closeForm()">取 消</el-button>
        <el-button type="primary" @click="addDistribution()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分销详情弹框 -->
    <el-dialog title="分销详情" :visible.sync="detailVisible" width="50%">
      <div class="detail_container">
        <div class="detail_item">
          <div style="width: 80px;">分销名：</div>
          <div style="margin-left: 20px;">{{ detailForm.label }}</div>
        </div>
        <div class="detail_item" style="margin-top: 12px;">
          <div style="width: 80px;">流水详情：</div>
          <div style="margin-left: 20px;font-size: 11px;font-weight: 700;">
            公司筛选：
          </div>
          <div>
            <el-input
              v-model="detailForm.companyName"
              style="width: 193px;"
              @input="getDetailList()"
              placeholder="请输入"
            ></el-input>
          </div>
          <div style="margin-left: 20px;font-size: 11px;font-weight: 700;">
            时间筛选：
          </div>
          <div>
            <el-date-picker
              v-model="detailForm.date"
              type="daterange"
              placeholder="选择日期"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="getDetailList()"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="detail_table">
          <el-table :data="detailList" border max-height="300">
            <el-table-column
              prop="companyName"
              label="公司"
              align="center"
              width="260"
            >
            </el-table-column>
            <el-table-column prop="name" label="销售金额" align="center">
              <template slot-scope="scope">
                <span style="color: red;">{{ scope.row.orderPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="佣金" align="center">
              <template slot-scope="scope">
                <span style="color: red;">{{ scope.row.commissionPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderNo"
              label="单号"
              align="center"
              width="160"
            >
            </el-table-column>
            <el-table-column prop="createTime" label="时间" align="center">
            </el-table-column>
          </el-table>
        </div>

        <div class="detail_total">
          <div>总销售额：</div>
          <div style="color: red;">{{ detailTotalAmount }}</div>
          <div style="margin-left: 24px;">总佣金：</div>
          <div style="color: red;">{{ detailCommissionAmount }}</div>
        </div>

        <div style="display: flex;justify-content: center;margin-top: 10px;">
          <!-- 分页组件 -->
          <Pagination
            v-bind:child-msg="pageparmB"
            @callFather="callFatherB"
          ></Pagination>
        </div>
      </div>
    </el-dialog>

    <!-- 二维码弹框 -->
    <el-dialog
      title="分销分享"
      :visible.sync="shareDialogVisible"
      :before-close="closeFormShare"
      width="30%"
    >
      <div class="share_container">
        <div class="share_item">
          <div class="label">二维码：</div>
          <img
            :src="shareForm.qrcode"
            alt=""
            style="width: 195px;height: 195px;"
          />
          <div class="down" @click="downloadIamge()">下载</div>
        </div>
        <div
          class="share_item"
          style="align-items: flex-start;margin-top: 20px;"
        >
          <div class="label">分享链接：</div>
          <div class="content">{{ shareForm.link }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from "../../components/Pagination";
import {
  getAgentTree,
  creatAgent,
  delAgent,
  getCompanyList,
  getEditData,
  updateAgent,
  creatAgentCustom,
  getUserByCompanyId,
  getAgentCode,
  getShortLink
} from "../../api/agent";
import { getAgentRecordList } from "../../api/agentRecord";
export default {
  components: {
    Pagination
  },
  data() {
    return {
      distributionTitle: "新增一级分销",
      distributionVisible: false,
      companyVisible: false,
      shareDialogVisible: false,
      detailVisible: false,
      editFlag: false,
      distributionForm: {
        id: "",
        name: "",
        companyID: "",
        profit: "",
        parentProfit: "",
        parentID: ""
      },
      //负责人
      principalPerson: {
        userName: "",
        phone: ""
      },
      detailForm: {
        label: "",
        companyName: "",
        date: [],
        agentID: ""
      },
      companyForm: {
        agentID: ""
      },
      //分销分享
      shareForm: {
        qrcode: "",
        link: ""
      },
      pageparmA: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      pageparmB: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      companyList: [],
      companyOptions: [],
      detailList: [],
      detailTotalAmount: 0,
      detailCommissionAmount: 0,
      agentRules: {
        name: [{ required: true, message: "请输入分销名", trigger: "blur" }],
        companyID: [
          { required: true, message: "请选择主体公司", trigger: "blur" }
        ],
        profit: [
          { required: true, message: "请输入公司利润点", trigger: "blur" }
        ],
        parentProfit: [
          { required: true, message: "请输入下级利润点", trigger: "blur" }
        ]
      },
      companyRules: {
        agentID: [{ required: true, message: "请选择公司名", trigger: "blur" }]
      },
      loading: false,
      menuList: [],
      tableData: [],
      currentCompanyId: "",
      currentCompanyName: ""
    };
  },
  created() {
    this.getAgentTree();
    this.getCompanyList();
    this.getCompanyList();
  },
  methods: {
    //获取树形结构数据
    async getAgentTree() {
      const res = await getAgentTree();
      if (res.code == 200) {
        this.menuList = JSON.parse(JSON.stringify(res.data));
        this.currentCompanyId = this.menuList[0].id;
        this.currentCompanyName = this.menuList[0].label;
        this.getList();
      }
    },

    //点击树状图获取客户公司列表
    customHandle(data) {
      this.currentCompanyId = data.id;
      this.currentCompanyName = data.label;
      this.pageparmA.pageIndex = 1;
      this.getList();
    },

    //获取分销列表
    async getList() {
      let list = {
        agentId: this.currentCompanyId,
        pageSize: this.pageparmA.pageSize,
        pageIndex: this.pageparmA.pageIndex
      };
      const res = await getUserByCompanyId(list);
      if (res.code == 200) {
        if (res.data) {
          this.tableData = res.data.items;
          this.pageparmA.total = res.data.totalCount;
        } else {
          this.tableData = [];
        }
      }
    },

    //点击添加一级分销
    addFirst() {
      this.distributionTitle = "新增一级分销";
      this.distributionVisible = true;
      this.editFlag = false;
      this.distributionForm = {
        name: "",
        companyID: "",
        profit: "",
        parentProfit: "",
        parentID: 0
      };
      this.principalPerson.userName = "";
      this.principalPerson.phone = "";
      this.getCompanyList();
    },

    // 添加/编辑分销
    addDistribution() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (!this.distributionForm.id) {
            this.distributionForm.profit = Number(this.distributionForm.profit);
            this.distributionForm.parentProfit = Number(
              this.distributionForm.parentProfit
            );
            const res = await creatAgent(this.distributionForm);
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.distributionVisible = false;
              this.getAgentTree();
            } else {
              this.$message.success(res.data.message);
            }
          } else {
            this.distributionForm.profit = Number(this.distributionForm.profit);
            this.distributionForm.parentProfit = Number(
              this.distributionForm.parentProfit
            );
            const res = await updateAgent(this.distributionForm);
            if (res.code == 200) {
              this.$message.success("编辑成功");
              this.distributionVisible = false;
              this.getAgentTree();
            } else {
              this.$message.success(res.data.message);
            }
          }
        }
      });
    },

    // 添加分销弹窗关闭校验
    closeForm() {
      this.$refs["ruleForm"].resetFields();
      this.distributionForm = {
        name: "",
        companyID: "",
        profit: "",
        parentProfit: "",
        parentID: 0
      };
      this.distributionVisible = false;
    },

    // 添加公司弹窗关闭校验
    closeFormCompany() {
      this.$refs["ruleFormCompany"].resetFields();
      this.companyForm = {
        agentID: ""
      };
      this.companyVisible = false;
    },

    //关闭分享弹框
    closeFormShare(done) {
      (this.shareForm = {
        qrcode: "",
        link: ""
      }),
        done();
    },

    //添加二级分销
    append(data) {
      this.distributionTitle = "新增二级分销";
      this.distributionVisible = true;
      this.distributionForm = {
        name: "",
        companyID: "",
        profit: "",
        parentProfit: "",
        parentID: data.id
      };
      this.menuList.forEach(item => {
        if (item.id == this.distributionForm.parentID) {
          this.distributionForm.parentName = item.label;
        }
      });
      this.getCompanyList();
    },

    //编辑分销
    async editHandle(data) {
      this.distributionTitle = "编辑" + data.label;
      this.editFlag = true;
      this.distributionVisible = true;
      const res = await getEditData({ id: data.id });
      if (res.code == 200) {
        this.distributionForm.id = res.data.id;
        this.distributionForm.name = res.data.name;
        this.distributionForm.companyID = res.data.companyID;
        this.distributionForm.profit = res.data.profit;
        this.distributionForm.parentProfit = res.data.parentProfit;
        this.distributionForm.parentID = res.data.parentID;
        this.distributionForm.parentName = res.data.parentName;
        this.principalPerson.userName = res.data.userName;
        this.principalPerson.phone = res.data.phone;
        this.companyList = [
          { id: res.data.companyID, name: res.data.companyName }
        ];
      }
    },

    //分销详情
    detailHandle(data) {
      this.detailVisible = true;
      this.detailForm.label = data.label;
      this.detailForm.agentID = data.id;
      this.getDetailList();
    },

    //分享二维码
    shareHandle(data) {
      this.shareDialogVisible = true;
      this.getAgentCode(data);
      this.getShortLink(data);
    },

    //获取二维码
    async getAgentCode(data) {
      let req = {
        agentId: data.id
      };
      const res = await getAgentCode(req);
      if (res.code == 200) {
        this.shareForm.qrcode = res.data;
      } else {
        this.shareForm.qrcode = "";
        this.$message.error(res.message);
      }
    },

    //获取短链接
    async getShortLink(data) {
      let req = {
        agentId: data.id
      };
      const res = await getShortLink(req);
      if (res.code == 200) {
        this.shareForm.link = res.data;
      } else {
        this.shareForm.link = "";
        this.$message.error(res.message);
      }
    },

    // 获取详情列表
    async getDetailList() {
      let req = {
        pageIndex: this.pageparmB.pageIndex,
        pageSize: this.pageparmB.pageSize,
        agentID: this.detailForm.agentID,
        companyName: this.detailForm.companyName,
        startTime: this.detailForm.date ? this.detailForm.date[0] : "",
        endTime: this.detailForm.date ? this.detailForm.date[1] : ""
      };
      const res = await getAgentRecordList(req);
      if (res.code == 200 && res.data) {
        this.detailList = res.data.items;
        this.pageparmB.total = res.data.totalCount;
        this.detailTotalAmount = res.data.totalAmount;
        this.detailCommissionAmount = res.data.commissionAmount;
      } else {
        this.detailList = [];
      }
    },

    //删除
    remove(data) {
      this.$confirm("确定删除吗？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const res = await delAgent({ id: data.id });
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.getAgentTree();
        }
      });
    },

    //查看
    viewDetail(val) {},

    // 主体公司模糊查询
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.getCompanyList(query);
        }, 200);
      } else {
        this.getCompanyList();
      }
    },

    //获取主体公司
    async getCompanyList(val) {
      let data = {
        pageIndex: 1,
        size: 999,
        name: val ? val : ""
      };
      let res = await getCompanyList(data);
      if (res.code == 200) {
        this.companyList = res.data;
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },

    // 客户公司模糊查询
    remoteMethodCompany(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.getCompanyList(query);
        }, 200);
      } else {
        this.getCompanyList("");
      }
    },

    //添加公司
    addCompanyConfirm() {
      this.$refs["ruleFormCompany"].validate(async valid => {
        if (valid) {
          let list = {
            companyID: this.companyForm.agentID,
            agentID: this.currentCompanyId
          };
          const res = await creatAgentCustom(list);
          if (res.code == 200) {
            this.$message.success("添加成功");
            this.companyVisible = false;
            this.getList();
          } else {
            this.$message.error(res.data.message);
          }
        }
      });
    },

    //下载图片
    downloadIamge() {
      const url = this.shareForm.qrcode;
      window.location.href = url;
    },

    // 分销列表分页插件事件
    callFatherA(parm) {
      this.pageparmA.pageIndex = parm.pageIndex;
      this.pageparmA.pageSize = parm.size;
      this.getList();
    },

    // 分销详情列表分页插件事件
    callFatherB(parm) {
      this.pageparmB.pageIndex = parm.pageIndex;
      this.pageparmB.pageSize = parm.size;
      this.getDetailList();
    }
  }
};
</script>
<style lang="less" scoped>
:deep(.menu .el-tree .el-tree-node .el-tree-node__content) {
  padding: 10px;
  font-size: 20px;
}
.container {
  display: flex;
}
.left_container {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  width: 380px;
  height: 80vh;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  margin: 20px;
  .add {
    cursor: pointer;
  }
  .label {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    padding-right: 35px;
    box-sizing: border-box;
    color: rgb(79, 79, 79);
    font-family: 思源黑体;
    font-size: 11px;
    font-weight: 500;
    background: rgb(243, 246, 250);
    margin-top: 5px;
  }
  .menu {
    .label_item {
      width: 50% !important;
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.right_container {
  flex: 1;
  background-color: #fff;
  height: 80vh;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  margin: 20px;
  margin-left: 0;
  position: relative;
  .nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .company {
      color: rgb(79, 79, 79);
      font-family: 思源黑体;
      font-size: 14px;
      font-weight: 400;
      display: flex;
      align-items: center;
    }
  }
}
.distribution_container {
  width: 100%;
  border-top: 1px solid rgb(235, 238, 245);
  border-right: 1px solid rgb(235, 238, 245);
  .collection {
    display: flex;
    width: 100%;
  }
  .company_item {
    display: flex;
    width: 50%;
    border-bottom: 1px solid rgb(235, 238, 245);
    .item_left {
      display: flex;
      align-items: center;

      .label {
        width: 154px;
        height: 80px;
        display: flex;
        align-items: center;
        color: rgb(126, 126, 126);
        font-family: 思源黑体;
        font-weight: 500;
        background: rgb(250, 250, 250);
        padding-left: 14px;
        box-sizing: border-box;
        border-left: 1px solid rgb(235, 238, 245);
        border-right: 1px solid rgb(235, 238, 245);
      }
    }
    .item_right {
      width: 100%;
      display: flex;
      align-items: center;
      padding: 0 14px;
      // border-right: 1px solid rgb(235, 238, 245);
      .content {
        color: rgb(91, 91, 91);
        font-family: 思源黑体;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
}
.detail_container {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
  .detail_item {
    color: rgb(69, 69, 69);
    font-family: 思源黑体;
    font-weight: 400;
    font-size: 16px;
    display: flex;
    align-items: center;
  }
  .detail_table {
    width: 80%;
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    margin-left: 100px;
  }
  .detail_total {
    width: 90%;
    display: flex;
    justify-content: flex-end;
    color: rgb(143, 135, 135);
    font-family: 思源黑体;
    font-size: 12px;
    font-weight: 400;
    margin-top: 10px;
  }
}
.share_container {
  margin: auto;
  .share_item {
    width: 70%;
    display: flex;
    align-items: flex-end;
    margin: auto;
    .label {
      width: 100px;
      text-align: right;
      color: rgb(69, 69, 69);
      font-family: 思源黑体;
      font-size: 16px;
      font-weight: 400;
    }
    .down {
      width: 66.83px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background: rgb(255, 255, 255);
      border: 1px solid rgb(200, 200, 200);
      border-radius: 2px;
      color: rgb(200, 200, 200);
      font-family: 思源黑体;
      font-size: 10px;
      font-weight: 700;
      cursor: pointer;
      margin-left: 10px;
    }
    .down:hover {
      background: #2e9cfe;
      color: #fff;
    }
    .content {
      flex: 1;
      color: rgb(69, 69, 69);
      font-family: 思源黑体;
      font-size: 12px;
      font-weight: 400;
      margin-left: 10px;
      padding-top: 3px;
    }
  }
}
</style>
